package ru.sviridov.sellandbuy.tasks.base;

import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;

import ru.sviridov.sellandbuy.json.AuthSerializer;
import ru.sviridov.sellandbuy.json.JSONErrorCode;
import ru.sviridov.sellandbuy.json.ResponseDeserializer;
import ru.sviridov.sellandbuy.model.IAuth;
import ru.sviridov.sellandbuy.model.IResponse;
import ru.sviridov.sellandbuy.model.Response;
import ru.sviridov.sellandbuy.tools.Session;
import ru.sviridov.sellandbuy.url.ServiceClient;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class BaseTask<Progress> extends AsyncTask<String, Progress, Response> {
	protected final TaskRecipient recipient;
	private WeakReference<Context> context; //TODO currently not used
	private int errorCode = HttpURLConnection.HTTP_OK;
	private IAuth queryParams = null;
	
	public BaseTask(Context context){
		this(context, new TaskRecipientStub());
	}
	
	public BaseTask(Context context, TaskRecipient recipient){
		this.recipient = recipient;
		this.context = new WeakReference<Context>(context);
	}

	/** transfer query params via post*/
	public void setQueryParams(IAuth queryParams){
		this.queryParams = queryParams;		
	}
	
	@Override
	protected final Response doInBackground(String... url) {
		GsonBuilder gBuilder = new GsonBuilder();
		gBuilder.serializeNulls();
		gBuilder.registerTypeAdapter(IAuth.class, new AuthSerializer());
		gBuilder.registerTypeAdapter(IResponse.class, new ResponseDeserializer());
		gBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);
		Gson gson = gBuilder.create();
		String params = gson.toJson(queryParams, IAuth.class);
		
		ServiceClient client = new ServiceClient();
		if(client.query(url[0], params)!=HttpURLConnection.HTTP_OK){
			errorCode = client.getErrorCode();
			return null;
		}
			
		return (Response) gson.fromJson(client.getResponse(), IResponse.class);
//		return parseInBackground(client, response);
	}

//	protected Response parseInBackground(ServiceClient client, Response response) {
//		return response;
//	}

	@Override
	protected final void onPostExecute(Response response) {
		if(response==null) {
			recipient.onURLError(context.get(),errorCode);
		}
		else {
			Session.setSession(context.get(), response.getSession()); 
			if(response.getErrorCode()==JSONErrorCode.OK) {
				recipient.onSuccess(context.get(), response);
			} else
				recipient.onJSONError(context.get(), response);
		}
	}

	@Override
	protected void onCancelled(Response response) {
		Log.i("SERVICE", "Task cancelled "+ getClass());
	}	
	
}